package common

import (
	"coursedesign/projectGo/model"
	"github.com/spf13/viper"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"strings"
)

var DB *gorm.DB

func InitDB() *gorm.DB {
	host := viper.GetString("datasource.host")
	user := viper.GetString("datasource.userName")
	password := viper.GetString("datasource.password")
	dbname := viper.GetString("datasource.database")
	port := viper.GetString("datasource.port")
	sslmode := "disable"
	timeZone := "Asia/Shanghai"

	var build strings.Builder // 连接字符串
	build.WriteString("host=")
	build.WriteString(host)
	build.WriteString(" user=")
	build.WriteString(user)
	build.WriteString(" password=")
	build.WriteString(password)
	build.WriteString(" dbname=")
	build.WriteString(dbname)
	build.WriteString(" port=")
	build.WriteString(port)
	build.WriteString(" sslmode=")
	build.WriteString(sslmode)
	build.WriteString(" TimeZone=")
	build.WriteString(timeZone)

	dsn := build.String() // 生成字符串

	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	}) // 连接postgresql
	if err != nil {
		panic("failed to connect database, err: " + err.Error())
	}

	db.AutoMigrate(&model.Manager{}) // 自动创建数据表

	DB = db

	return db
}

func GetDB() *gorm.DB {
	return DB
}
